<?php

namespace App\Http\Controllers;

use App\Constant;
use App\Models\BalanceLogModel;
use App\Models\CommissionHistory;
use App\Models\ManualDfMethod;
use App\Services\DfChannel\DfChannelFactory;
use Illuminate\Http\Request;
use App\Models\SellerWithdrawRequest;
use App\Models\Seller;
use App\Models\User;
use App\Models\Wallet;
use App\Models\Payment;
use App\Models\Product;
use App\Models\Order;
use Session;
use Throwable;
use DB;
use Auth;

class CommissionController extends Controller
{

    public function topup_to_seller(Request $request)
    {
        try {
            DB::beginTransaction();

            $payment = new Payment();
            $payment->withdraw_request_id = null;
            $payment->seller_id = Seller::findOrFail($request->seller_id)->user->id;
            $payment->user_type = Seller::findOrFail($request->seller_id)->user->user_type;
            $payment->amount = $request->amount;
            $payment->payment_details = \implode(',', ['topup', Auth::user()->user_type, Auth::user()->id]);
            $payment->payment_method = 'topup';
            //$payment->txn_code = $request->txn_code;
            $payment->saveOrFail();

            $wallet = new Wallet();
            $wallet->user_id = Seller::findOrFail($request->seller_id)->user_id;
            $wallet->payment_method = 'topup';
            $wallet->payment_details = null;
            $wallet->amount = $request->amount;
            $wallet->approval = 1;
            $wallet->offline_payment = 0;
            $wallet->reciept = null;
            $wallet->saveOrFail();

            Seller::findOrFail($request->seller_id)->user->increment('balance', $request->amount);

            DB::commit();
            flash(translate('Payment Successfully'))->success();
            return redirect()->back();
        } catch (Throwable $ex) {
            DB::rollBack();
        }
        flash(translate('Payment Failure' . $ex->getMessage()))->error();
        return redirect()->back();
    }

    /*public function topup_to_customer(Request $request)
    {
        
    }*/

    //redirect to payment controllers according to selected payment gateway for seller payment
    public function pay_to_seller(Request $request)
    {
        $post = $request->post();
        try {
            DB::beginTransaction();
            $trade_no = get_trade_no();
            // 处理提现申请
            $withdraw_request = SellerWithdrawRequest::findOrFail($request->withdraw_request_id);
            if($post['status'] == -1) {
                $withdraw_request->status = -1;
                $withdraw_request->viewed = 1;
                $withdraw_request->saveOrFail();
                $seller = $withdraw_request->user;

                $balance_log_model = BalanceLogModel::create([
                    'user_id' => $seller->id,
                    'type' => Constant::BALANCE_LOG_TYPE_WITHDRAW_REJECT,
                    'value_before' => $seller->balance,
                    'value' => $withdraw_request->amount,
                    'description' => "Withdraw Reject",
                    'trade_id' => $withdraw_request->id,
                ]);


                $seller->fill(['balance' => ($seller->balance + $withdraw_request->amount)])->save();
                DB::commit();
            } else {
                $withdraw_request->status = $request->channel_id > 0 ? Constant::NO : Constant::YES;
                $withdraw_request->viewed = 1;
                $withdraw_request->saveOrFail();
                // 处理调用记录
                $payment = new Payment();
                $payment->withdraw_request_id = $request->withdraw_request_id;
                $payment->seller_id = $withdraw_request->user_id;
                $payment->user_type = User::findOrFail($withdraw_request->user_id)->user_type;
                $payment->amount = $withdraw_request->amount;
                $payment->payment_details = null;
                $payment->payment_method = $request->payment_option;
                $payment->txn_code = $request->txn_code;
                $payment->channel_id = $request->channel_id;
                $payment->trade_no = $trade_no;
                $payment->saveOrFail();
                DB::commit();

                if ($payment->channel_id > 0) {
                    if (false === $payment->push()) {
                        flash(translate($payment->msg))->error();
                        return redirect()->back();
                    }
                }
            }

            flash(translate('Operation Successfully'))->success();
            return redirect()->back();
        } catch (Throwable $ex) {
            DB::rollBack();
        }
    }

    public function pay_to_customer(Request $request)
    {
        return $this->pay_to_seller($request);
    }

    //redirects to this method after successfull seller payment
    public function seller_payment_done($payment_data, $payment_details)
    {
        $seller = Seller::findOrFail($payment_data['seller_id']);
        //$seller->can_to_pay = $seller->can_to_pay - $payment_data['amount'];
        //$seller->save();

        $payment = new Payment;
        $payment->user_type = 'seller';
        $payment->seller_id = $seller->id;
        $payment->amount = $payment_data['amount'];
        $payment->payment_method = $payment_data['payment_method'];
        $payment->txn_code = $payment_data['txn_code'];
        $payment->payment_details = $payment_details;
        $payment->save();

        if ($payment_data['payment_withdraw'] == 'withdraw_request') {
            $seller_withdraw_request = SellerWithdrawRequest::findOrFail($payment_data['withdraw_request_id']);
            $seller_withdraw_request->status = '1';
            $seller_withdraw_request->viewed = '1';
            $seller_withdraw_request->save();
        }

        Session::forget('payment_data');
        Session::forget('payment_type');

        if ($payment_data['payment_withdraw'] == 'withdraw_request') {
            flash(translate('Payment completed'))->success();
            return redirect()->route('withdraw_requests_all');
        } else {
            flash(translate('Payment completed'))->error();
            return redirect()->back();
        }
    }

    //calculate seller commission after payment
    public function calculateCommission($order)
    {

        if ($order->payment_type == 'cash_on_delivery') {
            foreach ($order->orderDetails as $orderDetail) {
                $orderDetail->payment_status = 'paid';
                $orderDetail->save();
                $commission_percentage = 0;

                if (get_setting('vendor_commission_activation')) {
                    if (get_setting('category_wise_commission')) {
                        $commission_percentage = $orderDetail->product->category->commision_rate;
                    } else if ($orderDetail->product->user->user_type == 'seller') {
                        $commission_percentage = get_setting('vendor_commission');
                    }
                }
                if ($orderDetail->product->user->user_type == 'seller') {
                    $seller = $orderDetail->product->user->seller;
                    $admin_commission = ($orderDetail->price * $commission_percentage) / 100;

                    if (get_setting('product_manage_by_admin') == 1) {

                        $product = Product::where('id', $orderDetail->product_id)->first();

                        $seller_earning = $chajia = ($product['unit_price'] - $product['pprice']) * $orderDetail->quantity;

                        ######$seller_earning = ($orderDetail->tax +  $chajia ) - $admin_commission;
                        $seller->admin_to_pay += $seller_earning;
                    } else {
                        $seller_earning = ($orderDetail->tax + $orderDetail->shipping_cost + $orderDetail->price) - $admin_commission;
                        $seller->admin_to_pay -= $admin_commission;
                    }

                    $seller->save();

                    $commission_history = new CommissionHistory;
                    $commission_history->order_id = $order->id;
                    $commission_history->order_detail_id = $orderDetail->id;
                    $commission_history->seller_id = $orderDetail->seller_id;
                    $commission_history->admin_commission = $admin_commission;
                    $commission_history->seller_earning = $seller_earning;

                    $commission_history->save();
                }
            }
        } else {
            foreach ($order->orderDetails as $orderDetail) {
                $orderDetail->payment_status = 'paid';
                $orderDetail->save();
                $commission_percentage = 0;

                if (get_setting('vendor_commission_activation')) {
                    if (get_setting('category_wise_commission')) {
                        $commission_percentage = $orderDetail->product->category->commision_rate;
                    } else if ($orderDetail->product->user->user_type == 'seller') {
                        $commission_percentage = get_setting('vendor_commission');
                    }
                }

                if ($orderDetail->product->user->user_type == 'seller') {
                    $seller = $orderDetail->product->user->seller;
                    $admin_commission = ($orderDetail->price * $commission_percentage) / 100;

                    if (get_setting('product_manage_by_admin') == 1) {
                        $seller_earning = ($orderDetail->tax + $orderDetail->price) - $admin_commission;
                        $seller->admin_to_pay += $seller_earning;
                    } else {
                        $seller_earning = ($orderDetail->tax + $orderDetail->shipping_cost + $orderDetail->price) - $admin_commission;


                        $product = Product::where('id', $orderDetail->product_id)->first();


                        $seller_earning = $chajia = ($product['unit_price'] - $product['pprice']) * $orderDetail->quantity;
                        ###### $seller_earning = ($orderDetail->tax +  $chajia ) - $admin_commission;
                        $seller->admin_to_pay += $seller_earning;

                        #$seller->admin_to_pay += $seller_earning;
                    }

                    $order->seller_earning = $seller_earning;
                    $order->save();

                    $seller->save();

                    $commission_history = new CommissionHistory;
                    $commission_history->order_id = $order->id;
                    $commission_history->order_detail_id = $orderDetail->id;
                    $commission_history->seller_id = $orderDetail->seller_id;
                    $commission_history->admin_commission = $admin_commission;
                    $commission_history->seller_earning = $seller_earning;

                    $commission_history->save();
                }
            }
            if ($order->seller != null) {
                $seller->admin_to_pay -= $order->coupon_discount;
                $seller->save();
            }
        }

        $o = Order::findOrFail($order->id);
        $o->profit = 0; //$seller_earning;
        $o->save();
    }
}
